<template>
  <div class="app-container">
    <template>
      <el-row>
        <el-col :span="24">
          <div class="h_top">
            <div class="search_box">
              <el-form :model="query" :inline="true">
                <el-row :gutter="10">
                  <el-col :xl="3" :lg="3" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">编 号</div>
                      <el-input v-model="query.coding" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">名 称</div>
                      <el-input v-model="query.name" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">创建时间</div>
                      <el-date-picker v-model="query.create_time" type="datetimerange" placeholder="" value-format="yyyy-MM-dd HH:mm:ss" size="mini" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">验证时间</div>
                      <el-date-picker v-model="query.verify_date" type="datetimerange" placeholder="" value-format="yyyy-MM-dd HH:mm:ss" size="mini" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="2" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">领用人</div>
                      <el-input v-model="query.apply_admin" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="2" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">领用班组</div>
                      <el-input v-model="query.apply_class" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="2" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">申请车间</div>
                      <el-select v-model="query.workshop_id" size="mini">
                        <el-option v-for="(item, workshopIndex) in toolAppearWorkshop" :key="workshopIndex" :value="workshopIndex" :label="item" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="2" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">类型</div>
                      <el-select v-model="query.kind" size="mini">
                        <el-option v-for="(item, kindIndex) in toolAppearKind" :key="kindIndex" :label="item" :value="kindIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="2" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">状 态</div>
                      <el-select v-model="query.status" size="mini">
                        <el-option v-for="(item, appearIndex) in toolAppearStatus" :key="appearIndex" :label="item" :value="appearIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="2" :md="2" :sm="2">
                    <el-form-item>
                      <div class="search_label">操 作</div>
                      <el-button type="primary" icon="el-icon-search" size="mini" @click="search">查找</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div class="toolBars">
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-document-add" size="mini" @click="addHandler">增加</el-button>
              </div>
              <div class="buttonBox" hidden>
                <el-button type="primary" icon="el-icon-printer" size="mini" @click="dialogTableVisible = true">导出</el-button>
                <el-dialog title="工具出库导出" :visible.sync="dialogTableVisible" width="45%" center>
                  <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" class="marginLeft20" @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="needExport" class="marginLeft20" @change="handleText">
                    <el-checkbox v-for="item in needExportArray" :key="item" class="width73" :label="item">{{ item }}</el-checkbox>
                  </el-checkbox-group>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogTableVisible = false">取 消</el-button>
                    <el-button type="primary" @click="exportHandler">确 定</el-button>
                  </div>
                </el-dialog>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-box" size="mini" :disabled="!selection.length" @click="archive">归档</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-delete" :disabled="!selection.length" size="mini" @click="remove">删除</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="reloadHandler">刷新</el-button>
              </div>
              <div class="fr">总数：<span>{{ total }}</span></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </template>
    <div>
      <el-table v-loading="loading" :data="appearList" size="small" stripe border :header-cell-style="{background:'#eef1f6',color:'#606266'}" style="width: 100%" @selection-change="selectionHandler">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="coding" label="编号" align="center" width="200" />
        <el-table-column prop="name" label="名称" width="200" align="center" />
        <el-table-column prop="status" label="状态" width="150" align="center" :formatter="statusFormat" />
        <el-table-column prop="create_time" label="创建时间" width="200" align="center" />
        <el-table-column prop="apply_admin" label="领用人" width="" align="center" />
        <el-table-column prop="apply_class" label="领用班组" width="150" align="center" />
        <el-table-column prop="workshop_id" label="领用车间" width="150" align="center" :formatter="workshopFormat" />
        <el-table-column prop="kind" label="类型" width="150" align="center" :formatter="kindFormat" />
        <el-table-column v-if="listHandle" fixed="right" label="操作" width="200" align="center">
          <template scope="scope">
            <el-button type="primary" size="mini" @click="updateHandler(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="mini" @click="confirmDel(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="page" background :page-size="query.limit" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
    </div>
  </div>
</template>
<script>
import API from '@/api/tool/appear'
import { toolAppearStatus, toolAppearWorkshop, toolAppearKind } from '@/utils/options'
import xlsx from 'xlsx'
import exportMethod from '@/mixins/export'
export default {
  inject: ['reload', 'goUrl', 'delOne', 'delMany', 'getToolAppearStatusFormat', 'archives'],
  components: {},
  mixins: [exportMethod],
  data() {
    return {
      checkAll: false,
      isIndeterminate: true,
      dialogTableVisible: false,
      needExport: [],
      needExportArray: ['编号', '名称', '状态', '申请人', '仓库', '出库时间', '验证人员', '验证时间', '负责人'],
      loading: false,
      total: 0,
      query: { page: 1, limit: 15 },
      appearList: [],
      selection: [],
      toolAppearStatus,
      toolAppearWorkshop,
      toolAppearKind
    }
  },
  computed: {
    tableMaxHeight() {
      return window.innerHeight - 260 + 'px'
    },
    listHandle() {
      return this.$store.state.settings.listHandle
    }
  },
  watch: {},
  created() {
    const query = JSON.parse(sessionStorage.getItem('query'))
    if (query) {
      this.query = query
      sessionStorage.removeItem('query')
    }
    this.index()
  },
  methods: {
    search() {
      this.query.page = 1
      this.index()
    },
    selectionHandler(selection) {
      this.selection = selection
    },
    index() {
      this.loading = true
      API.appearList(this.query).then(response => {
        this.total = response.data.total
        this.appearList = response.data.data
      }).finally(() => {
        this.loading = false
      })
    },
    handleCheckAllChange(val) {
      this.needExport = val ? this.needExportArray : []
      this.isIndeterminate = false
    },
    handleText(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.needExportArray.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.needExportArray.length
    },
    exportHandler() {
      if (this.selection.length === 0) {
        this.$message.error('请选择要到导出的数据')
        return false
      }
      this.selection.forEach((item) => {
        if (item.status === 0) {
          item.statusOut = '创建'
        } else if (item.status === 1) {
          item.statusOut = '审核完成'
        } else if (item.status === 2) {
          item.statusOut = '已领件'
        } else if (item.status === 3) {
          item.statusOut = '归档'
        }
        if (item.verify_admin) {
          item.v_name = item.verify_admin.name
          item.v_date = item.verify_date
        } else {
          item.v_name = '未审核'
          item.v_date = '未审核'
        }
      })
      const data = []
      const titleObj = {
        'coding': '编号',
        'name': '名称',
        'statusOut': '状态',
        'apply_admin.name': '申请人',
        'stores.name': '仓库',
        'appear_date': '出库时间',
        'v_name': '验证人员',
        'v_date': '验证时间',
        'admin.name': '负责人'
      }
      if (this.needExport.length) {
        const title = []
        for (const key of this.needExport) {
          title.push(key)
        }
        data.push(title)
      } else {
        data.push(Object.values(titleObj))
      }
      const excelNeedExport = []
      for (const keys of this.needExport) {
        const thisKey = Object.keys(titleObj).find(key => titleObj[key] === keys)
        excelNeedExport.push(thisKey)
      }
      let fieldOut = 1
      this.selection.forEach((item) => {
        if (excelNeedExport.length) {
          const d = []
          for (const key of excelNeedExport) {
            if (key.includes('.')) {
              let value = item
              const tag = key.split('.')
              for (const k of tag) {
                value = value[k]
              }
              d.push(value)
            } else {
              d.push(item[key])
            }
          }
          data.push(d)
        } else {
          this.$message.error('请选择要到导出的字段')
          fieldOut = 2
        }
      })
      if (fieldOut === 1) {
        const workbook = {
          SheetNames: ['toolAppear'],
          Sheets: {
            'toolAppear': xlsx.utils.aoa_to_sheet(data)
          }
        }
        this.exportExec(workbook, '工具出库单数据报表.xlsx')
      }
    },
    archive() {
      const selection = this.selection
      this.archives(API, selection)
    },
    remove() {
      const selection = this.selection
      this.delMany(API, selection)
    },
    confirmDel(id) {
      this.delOne(API, id, false)
    },
    addHandler() {
      this.goUrl('/tool/appear/appear_add')
    },
    updateHandler(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const url = `/tool/appear/appear_edit/${id}`
      this.goUrl(url)
    },
    reloadHandler() {
      this.reload()
    },
    statusFormat(row) {
      return this.getToolAppearStatusFormat(row)
    },
    kindFormat(row) {
      if (row.kind === 0) {
        return '领用'
      } else if (row.kind === 1) {
        return '借用'
      } else if (row.kind === 2) {
        return '以旧换新'
      }
    },
    workshopFormat(row) {
      if (row.workshop_id === 0) {
        return '车身车间'
      } else if (row.workshop_id === 1) {
        return '涂装车间'
      } else if (row.workshop_id === 2) {
        return '总装车间'
      } else if (row.workshop_id === 2) {
        return '冲压车间'
      } else if (row.workshop_id === 3) {
        return '质量部'
      } else if (row.workshop_id === 4) {
        return '生产管理部'
      } else if (row.workshop_id === 5) {
        return '设备动力部'
      } else if (row.workshop_id === 6) {
        return '生产技术部'
      }
    }
  }
}
</script>
